<template>
  <div class="resume">
    <div>
      <div class="title">
        <h1 style="color: #4D7181;font-size: 40px">个人简历</h1>
        <div>
          <CopyOutlined class="icon"/>
          <UserOutlined class="icon"/>
        </div>

      </div>
    </div>
    <div style="border: 2px solid #4D7181; padding: 20px;border-top: 30px solid #4D7181; border-radius: 10px">


      <a-form
          ref="formRef"
          :label-col="labelCol"
          :model="formState"
          :rules="rules"
          :wrapper-col="wrapperCol"
      >
        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">基本信息</a-divider>
        <div class="basic">

          <div class="basicInfo">
            <a-form-item ref="student_name" label="姓名" name="student_name" style="width: 50%">
              <a-input v-model:value="formState.student_name" :bordered="isBordered"  :disabled="!isBordered"/>
            </a-form-item>

            <a-form-item ref="student_age" label="年龄" name="student_age" style="width: 50%">
              <a-input v-model:value="formState.student_age" :bordered="isBordered"  :disabled="!isBordered"/>
            </a-form-item>

            <a-form-item ref="student_sex" label="性别" name="student_sex" style="width: 50%">
              <a-input v-model:value="formState.student_sex" :bordered="isBordered"  :disabled="!isBordered"/>
            </a-form-item>

            <a-form-item ref="student_address" label="地址" name="student_address">
              <a-input v-model:value="formState.student_address" :bordered="isBordered"  :disabled="!isBordered" style="width: 300px"/>
            </a-form-item>

            <a-form-item ref="student_contact" label="电话" name="student_contact">
              <a-input v-model:value="formState.student_contact" :bordered="isBordered"  :disabled="!isBordered"/>
            </a-form-item>

            <a-form-item ref="student_email" label="邮箱" name="student_email">
              <a-input v-model:value="formState.student_email" :bordered="isBordered"  :disabled="!isBordered"/>
            </a-form-item>
          </div>
          <div class="update">
            <a-upload
                v-model:file-list="fileList"
                :before-upload="beforeUpload"
                :disabled="!isBordered"
                :show-upload-list="false"
                action="http://localhost:8080/file/upload"
                class="avatar-uploader"
                list-type="picture-card"
                name="file"
                @change="handleChange"
            >
              <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 120px; height: 170px;"/>
              <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text" >Upload</div>
              </div>
            </a-upload>
          </div>
        </div>


        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">教育背景</a-divider>
        <div class="school">

          <a-form-item ref="student_highest_education" label="最高学历" name="student_highest_education">
            <a-select v-model:value="formState.student_highest_education"  :bordered="isBordered"  :disabled="!isBordered" placeholder="请选择最高学历！">
              <a-select-option value="大专">大专</a-select-option>
              <a-select-option value="本科">本科</a-select-option>
              <a-select-option value="硕士">硕士</a-select-option>
              <a-select-option value="博士">博士</a-select-option>
              <a-select-option value="其他">其他</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item ref="student_graduation" label="毕业院校"
                       name="student_graduation">
            <a-input v-model:value="formState.student_graduation" :bordered="isBordered"  :disabled="!isBordered"/>
          </a-form-item>

          <a-form-item ref="student_major" label="专业"
                       name="student_major">
            <a-input v-model:value="formState.student_major" :bordered="isBordered"  :disabled="!isBordered"/>
          </a-form-item>

          <a-form-item ref="student_graduation_year" :wrapperCol="{ span: 12 }" label="毕业时间"
                       name="student_graduation_year">
            <a-date-picker v-model:value="formState.student_graduation_year" :bordered="isBordered"  :disabled="!isBordered"/>
          </a-form-item>

          <a-form-item ref="student_gpa" :wrapperCol="{ span: 12 }" label="成绩"
                       name="student_gpa">
            <a-input v-model:value="formState.student_gpa" :bordered="isBordered"  :disabled="!isBordered"/>
          </a-form-item>

          <a-form-item ref="student_campus_experience" :wrapperCol="{ span: 12 }" label="校园经历"
                       name="student_campus_experience">
            <a-textarea v-model:value="formState.student_campus_experience"
                        :auto-size="{minRows: 3, maxRows: 10}"
                        :bordered="isBordered"
                        :disabled="!isBordered"
                        :maxlength="300"
                        show-count
                        style="width: 800px"
            />
          </a-form-item>

          <a-form-item ref="student_honour" label="荣誉奖项" name="student_honour">
            <a-textarea v-model:value="formState.student_honour"
                        :auto-size="{minRows: 3, maxRows: 10}"
                        :bordered="isBordered"
                        :disabled="!isBordered"
                        :maxlength="300"
                        show-count
                        style="width: 800px"
            />
          </a-form-item>
        </div>
        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">技能特长</a-divider>
        <div class="school">
          <a-form-item ref="student_skills" :wrapperCol="{ span: 12 }"
                       label="专业技能" name="student_skills">
            <a-textarea v-model:value="formState.student_skills"
                        :auto-size="{minRows: 3, maxRows: 10}"
                        :bordered="isBordered"
                        :disabled="!isBordered"
                        :maxlength="600"
                        show-count
                        style="width: 800px"
            />
          </a-form-item>
        </div>
        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">实习经历</a-divider>
        <div class="school">
          <a-form-item ref="student_year_work" :wrapperCol="{ span: 12 }" label="实习时间"
                       name="student_year_work">
            <a-input v-model:value="formState.student_year_work" :bordered="isBordered"  :disabled="!isBordered" style="width: auto"/>
          </a-form-item>

          <a-form-item ref="student_internship_company" :wrapperCol="{ span: 12 }" label="实习公司"
                       name="student_internship_company">
            <a-input v-model:value="formState.student_internship_company" :bordered="isBordered"  :disabled="!isBordered"/>
          </a-form-item>

          <a-form-item ref="student_key_responsibilities" label="主要职责" name="student_key_responsibilities">
            <a-textarea v-model:value="formState.student_key_responsibilities"
                        :auto-size="{minRows: 3, maxRows: 20}"
                        :bordered="isBordered"
                        :disabled="!isBordered"
                        :maxlength="600"
                        show-count
                        style="width: 800px"
            />
          </a-form-item>
        </div>
        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">项目经验</a-divider>
        <div class="school">
          <a-form-item ref="student_projects" label="参与项目" name="student_projects">
            <a-textarea v-model:value="formState.student_projects"
                        :auto-size="{minRows: 3, maxRows: 20}"
                        :bordered="isBordered"
                        :disabled="!isBordered"
                        :maxlength="1000"
                        show-count
                        style="width: 800px"
            />
          </a-form-item>
        </div>
        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">自我评价</a-divider>
        <div class="school">
          <a-form-item ref="student_personal" label="个人简介-特长" name="student_personal">
            <a-textarea v-model:value="formState.student_personal"
                        :auto-size="{minRows: 2, maxRows: 20}"
                        :bordered="isBordered"
                        :disabled="!isBordered"
                        :maxlength="600"
                        show-count
                        style="width: 800px "
            />
          </a-form-item>
        </div>
        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">资质审核</a-divider>
        <div class="school">
          <a-form-item ref="student_certification_status" label="审核状态"
                       name="student_certification_status" style="width: 800px">
            <a-input v-model:value="formState.student_certification_status" :bordered="isBordered"
                     :disabled="true"/>
          </a-form-item>
          <div v-show="formState.student_certification_status==='审核不通过'">
            <a-form-item ref="student_certification_refuse" label="拒绝原因"
                         name="student_certification_refuse">
              <a-textarea v-model:value="formState.student_certification_refuse"
                          :auto-size="{minRows: 3, maxRows: 20}"
                          show-count
                          style="width: 500px"
              />
            </a-form-item>
          </div>
          <a-form-item ref="student_name" label="上传资质" name="student_name" style="width: 800px">
            <a-upload
                v-model:file-list="certificateList"
                name="file"
                action="http://localhost:8080/file/upload"
                :headers="headers"
                @change="handleChangeVerification"
                @remove="handleRemove"

            >
              <a-button :disabled="!isBordered">
                <upload-outlined></upload-outlined>
                请上学生证，学信网截图，学生卡相关学生资质文件
              </a-button>
            </a-upload>
          </a-form-item>
        </div>
        <a-col :span="24">
          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <div>
              <div v-if="isSave">
                <div style="display:flex;">
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定保存吗？" @confirm="save">
                    <a-button style="width:200px" type="primary">保存</a-button>
                  </a-popconfirm>
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定重置吗？" @confirm="resetForm">
                    <a-button type="primary" danger style="margin-left: 60px; width:200px">重置</a-button>
                  </a-popconfirm>
                </div>
              </div>
              <div v-else>
                <div v-if="isUpdate" style="display:flex;">
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定保存吗？" @confirm="update">
                    <a-button style="width:200px" type="primary">保存</a-button>
                  </a-popconfirm>

                  <a-button style="margin-left: 60px; width:200px" @click="cancel">取消</a-button>

                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定重置吗？" @confirm="resetForm">
                    <a-button type="primary" danger style="margin-left: 60px; width:200px">重置</a-button>
                  </a-popconfirm>
                </div>
                <div v-else>
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定修改吗？" @confirm="isupdate">
                    <a-button style="width:200px" type="primary">修改</a-button>
                  </a-popconfirm>

                  <a-button style="margin-left: 60px; width:200px" @click="goBack">返回</a-button>

                </div>
              </div>
            </div>

          </a-form-item>
        </a-col>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import {h, onMounted, reactive, ref, toRaw} from 'vue';
//修改提示框
import {CopyOutlined, SmileOutlined, UserOutlined} from '@ant-design/icons-vue';
//获取当前登录用户信息
import {useUserStore} from "@/stores/user.js";
import {addResumeAPI, queryResumeByStudentUserIdAPI, updateStudentByIdAPI} from "@/apis/student.js";
import {message, notification} from "ant-design-vue";
import moment from "moment";
import {useRouter} from 'vue-router';

const formRef = ref();
const formState = reactive({
  studentCertificate:'',
  studentCertificateFile:'',
  student_certification_status:'',
  student_certification_refuse:'',
  student_name: '',
  student_sex: '',
  student_age: '',
  student_contact: '',
  student_email: '',
  student_address: '',
  student_highest_education: '',
  student_campus_experience: '',
  student_graduation: '',
  student_major: '',
  student_graduation_year: '',
  student_gpa: '',
  student_honour: '',
  student_skills: '',
  student_year_work: '',
  student_internship_company: '',
  student_key_responsibilities: '',
  student_projects: '',
  student_personal: '',
  student_imgUrl: '',
  /**
   * 用户账号
   */
  account: '',

  /**
   * 用户角色
   */
  userRole: '',
  studentId: '',
});
const rules = {
  student_certification_status: [
    {
      required: true,
      trigger: 'change',
    },
  ],
  student_name: [
    {
      required: true,
      message: '请输入您的名字！',
      trigger: 'change',
    },
  ],
  student_sex: [
    {
      required: true,
      message: '请选择您的性别！',
      trigger: 'change',
    },
  ],
  student_age: [
    {
      required: true,
      message: '请输入您的年龄！',
      trigger: 'change',
    },
    {
      pattern: /^[0-9]+$/,
      message: '年龄必须为数字！',
      trigger: 'change',
    },
  ],
  student_contact: [
    {
      required: true,
      message: '请输入您的电话！',
      trigger: 'change',
    }
  ],
  student_email: [
    {
      required: true,
      message: '请输入您的邮箱！',
      trigger: 'change',
    }
  ],
  student_address: [
    {
      required: true,
      message: '请输入您的地址！',
      trigger: 'change',
    }
  ],
  student_highest_education: [
    {
      required: true,
      message: '请输入您的最高学历！',
      trigger: 'change',
    }
  ],

  student_graduation: [
    {
      required: true,
      message: '请输入您的毕业院校！',
      trigger: 'change',
    }
  ],
  student_major: [
    {
      required: true,
      message: '请输入您的专业！',
      trigger: 'change',
    }
  ],
  student_graduation_year: [
    {
      required: true,
      message: '请选择您的毕业时间！',
      trigger: 'change',
    }
  ],
  student_gpa: [
    {
      required: true,
      message: '请输入您的成绩-GPA！',
      trigger: 'change',
    }
  ],
  student_campus_experience: [
    {
      required: true,
      message: '请输入您的校园经历！',
      trigger: 'change',
    }
  ],
  student_honour: [
    {
      required: true,
      message: '请输入您的荣誉奖项！',
      trigger: 'change',
    }
  ],
  student_skills: [
    {
      required: true,
      message: '请输入您的专业技能！',
      trigger: 'change',
    }
  ],
  student_year_work: [
    {
      required: true,
      message: '请输入您的实习时间！',
      trigger: 'change',
    }
  ],
  student_internship_company: [
    {
      required: true,
      message: '请输入您的实习公司！',
      trigger: 'change',
    }
  ],
  student_key_responsibilities: [
    {
      required: true,
      message: '请输入您的主要职责！',
      trigger: 'change',
    }
  ],
  student_projects: [
    {
      required: true,
      message: '请输入您参与的项目-描述！',
      trigger: 'change',
    }
  ],
  student_personal: [
    {
      required: true,
      message: '请输入您的个人简介-特长！',
      trigger: 'change',
    }
  ]
};
const useStore = useUserStore();
const save = () => {
  formRef.value
      .validate()
      .then(async () => {
        formState.account = useStore.userInfo.account;
        formState.userRole = useStore.userInfo.userRole;
        formState.student_certification_status = '审核中';
        formState.studentCertificate='未认证';
        formState.studentCertificateFile=list.value.map((file)=>{
          return file;
        }).join(',');
        const res = await addResumeAPI(formState);
        console.log(res);
        if (res.data.flag) {
          success(res.data.message);
        } else {
          console.log('error submit!', toRaw(formState));
        }
      })
      .catch(error => {
        console.log('error', error);
      });
};
const isUpdate = ref(false);//是否修改
const isBordered = ref(false);//是否边框
const isupdate = () => {//修改按钮
  if(formState.student_certification_status === '审核中'){
    openNotification("学生信息正在审核中,不可修改，请耐心等待！", "red", 'top');
  }else {
    isUpdate.value = true;
    isBordered.value = true;
    openNotification("点击照片或输入框均可修改！", "green", 'top');
  }
}
const update = () => {
  console.log("修改"+JSON.stringify(list.value));
  formRef.value
      .validate()
      .then(async () => {
        formState.student_certification_status = '审核中';
        formState.student_certification_refuse='';
        formState.studentCertificate='未认证';
        formState.studentCertificateFile=list.value.map((file)=>{
          return file;
        }).join(',');
        const res = await updateStudentByIdAPI(formState);
        console.log(res);
        if (res.data.flag) {
          success("修改成功，请等待审核！");
          openNotification("已提交审核！", "#52C41A");
          // 设置一个定时器，在1秒后刷新页面
          setTimeout(() => {
            window.location.reload();
          }, 1000); // 1000毫秒 = 1秒
        } else {
          console.log('error submit!', toRaw(formState));
        }
      })
      .catch(error => {
        console.log('error', error);
      });
};

const success = (msg) => {
  message.success(msg);
};

//重置后是否刷新
const isRefresh = ref(false);
const resetForm = () => {
  formRef.value.resetFields();
  isRefresh.value = true;
};

//控制按钮
const isSave = ref();//是否保存
//获取数据
//获取当前登录用户信息

const studentUserId = ref(useStore.userInfo.userId);
const getData = async (studentUserId) => {
  const res = await queryResumeByStudentUserIdAPI(studentUserId.value)
  if (res.data.data == null) {
    isSave.value = true;
  } else {
    isSave.value = false;
  }

  formState.studentId = res.data.data.studentId;
  formState.student_name = res.data.data.studentName;
  formState.studentCertificate=res.data.data.studentCertificate;
  formState.studentCertificateFile=res.data.data.studentCertificateFile;
  if(res.data.data.studentCertificateFile!=null&&res.data.data.studentCertificateFile!==''){
    certificateList.value=res.data.data.studentCertificateFile.split(',').map((file)=>{
      return {
        name: file,
        url: file,
      };
    })
    len=certificateList.value.length;
    list.value=res.data.data.studentCertificateFile.split(',');
    console.log('len开始长度：'+JSON.stringify(certificateList.value.length))
  }else {
    certificateList.value=[];
    len=0;
  }
  formState.student_certification_refuse = res.data.data.studentCertificationRefuse;
  formState.student_certification_status = res.data.data.studentCertificationStatus;



  formState.student_imgUrl = res.data.data.studentImgurl;
  formState.student_sex = res.data.data.studentSex;
  formState.student_age = res.data.data.studentAge;
  formState.student_contact = res.data.data.studentContact;
  formState.student_email = res.data.data.studentEmail;
  formState.student_address = res.data.data.studentAddress;
  formState.student_highest_education = res.data.data.studentHighestEducation;
  formState.student_graduation = res.data.data.studentGraduation;
  formState.student_major = res.data.data.studentMajor;
  formState.student_graduation_year = moment(res.data.data.studentGraduationYear, 'YYYY-MM-DD');
  formState.student_gpa = res.data.data.studentGpa;
  formState.student_campus_experience = res.data.data.studentCampusExperience;
  formState.student_honour = res.data.data.studentHonour;
  formState.student_skills = res.data.data.studentSkills;
  formState.student_year_work = res.data.data.studentYearWork;
  formState.student_internship_company = res.data.data.studentInternshipCompany;
  formState.student_key_responsibilities = res.data.data.studentKeyResponsibilities;
  formState.student_projects = res.data.data.studentProjects;
  formState.student_personal = res.data.data.studentPersonal;

  //获取图片
  imageUrl.value = "http://localhost:8080/file/download?name=" + res.data.data.studentImgurl;
  console.log(imageUrl.value)
}


//生命周期
onMounted(() => {
  getData(studentUserId);
});

//上传照片
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref('');
const handleChange = info => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, base64Url => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
    formState.student_imgUrl = fileList.value[0].response.data;
    console.log(formState.student_imgUrl)

  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};
const beforeUpload = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

//提示框
const openNotification = (des, col, placement) => {
  notification.open({
    message: '温馨提示！！！',
    description: des, placement,
    icon: () =>
        h(SmileOutlined, {
          style: {color: col},
        }),
  });
};

const router = useRouter();
const goBack = () => {
  router.go(-1); // -1 表示返回上一个页面
}
const cancel = () => {
  isSave.value = false;
  isUpdate.value = false;
  isBordered.value = false;
  if (isRefresh.value) {
    // 设置一个定时器，1秒（1000毫秒）后执行页面刷新
    setTimeout(function () {
      location.reload(); // 刷新当前页面
    }, 500);
  }
}

//上传资质
const list=ref([]);//资质列表
const certificateList = ref([]);
const headers = {
  authorization: 'authorization-text',
};
let len//认证的列表从长度，用于判断是新增还是删除
const handleChangeVerification = info => {
  if (info.file.status !== 'uploading') {
    console.log('文件长度：'+certificateList.value.length+"   len长度："+len)
    if(certificateList.value.length>len){
      len=len+1;
      console.log("上传文件"+JSON.stringify(info.file.response.data));
      list.value.push(info.file.response.data);
    }

  }
  if (info.file.status === 'done') {
    message.success(`${info.file.name} file uploaded successfully`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};

function handleRemove(e) {
  console.log('删除了', JSON.stringify(e.name));
  list.value = list.value.filter(name=>name!==e.name);
  console.log("删除后"+JSON.stringify(list.value))
  len=len-1;
}


</script>
<style lang="scss" scoped>
.resume {
  margin: 5px;
  padding: 20px 60px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1);
  border-radius: 30px; /* 你可以调整这个值来改变圆角的大小 */

  .title {
    display: flex;
    justify-content: space-between;
    //border-bottom: 15px solid #4D7181;

    .icon {
      font-size: 35px;
      padding: 15px;
      color: white;
      margin-right: 20px;
      background-color: #C09E66;
      border-radius: 50px;
      margin-bottom: 10px;
    }
  }

  .basic {
    display: flex;
    padding-left: 30px;
    justify-content: space-between;

    .basicInfo {
      width: 70%;
      height: 100%;
      display: flex;
      flex-wrap: wrap; /* 允许子元素换行 */
      gap: 0 30px; /* 设置水平间距为10px，垂直间距为0 */
    }

    .update {
      margin-right: 100px;
    }
  }

  .school {
    width: 100%;
    padding-left: 30px;
    justify-content: space-between;
    display: flex;

    flex-wrap: wrap; /* 允许子元素换行 */
    gap: 0 30px; /* 设置水平间距为10px，垂直间距为0 */
  }
}

:deep(.ant-form-item) {
  margin-bottom: 10px;
}

:deep(.ant-upload-wrapper.ant-upload-picture-card-wrapper.ant-upload.ant-upload-select) {
  border: 0;
  height: 170px;
  width: 150px;
}

/* 如果组件不在 Shadow DOM 中 */
.ant-upload-wrapper.ant-upload-picture-card-wrapper.ant-upload.ant-upload-select {
  border: none; /* 移除边框 */
  height: 170px;
  width: 150px;
}

</style>

